<template>
  <div>
    <a-spin :spinning="spinning">
      <el-card>
        <template #header>
          <div class="card-header" style="display: flex; justify-content: center">
            <el-button class="button" @click="getView('左视图')" text>主视图</el-button>
            <el-button class="button" @click="getView('右视图')" text>左视图</el-button>
          </div>
        </template>
        <div>
          <div ref="chartContainer" style="width: 100%; height: 70vh"></div>
        </div>
      </el-card>
    </a-spin>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import "echarts-gl";
import html2canvas from "html2canvas";
import WellAnalysis from '@/api/v3/mechanical.js'
import WellSurvey from "@/api/survey/survey.js";
import { upFile } from "@/api/file/file.js";
import { getOne } from "@/api/geo/lithology.js";
import useApp from "@/hooks";
const { $ } = useApp();
const spinning = ref(false);
const chartContainer = ref(null);
const chart = ref();
const holeData = ref([]);
const svgUrl = ref();
const pixelCoord = ref([0, 0]);
const headPixelCoord = ref([0, 0]);
const coord = ref([]);
const lithologyImg = ref([]);
const props = defineProps({
  echartsData: Object,
  pass: {
    type: Array,
    default: [],
  },
});
onMounted(() => {
  // getData()
});
watch([() => props.echartsData, () => props.pass], () => {
  //清空画板
  // console.log("props.echartsData", props.echartsData);
  if (chart.value != undefined) {
    chart.value.clear();
  }
  getData();
});
function getData() {
  var wellId = localStorage.getItem("wellId"); //bucketName
  // var fileId = localStorage.getItem("fileId");
  // // console.log('Echart-fileId', fileId, fileId == 'undefined');
  // if (fileId == 'undefined') {
  //   console.log('测井数据不存在');
  //   spinning.value = false;
  // } else {
  //   console.log('测井数据存在');
  //   spinning.value = true;
  //   let isAddPoint = localStorage.getItem("isAddPoint")
  //   console.log('isAddPoint', isAddPoint);
  //   //每隔1米测深提供一个xyz轴
  //   WellAnalysis.interWell(wellId, 1, isAddPoint).then((res) => {
  //     // console.log("interWell", res);
  //     holeData.value = res.content;
  //     renderChart(holeData.value, svgUrl.value);
  //   });
  // }
  WellSurvey.latestSurvey(wellId).then(response => {
    // console.log("response", response);
    if (response.wellId) {
      console.log('测井数据存在');
      spinning.value = true;
      let isAddPoint = response.skew
      //每隔1米测深提供一个xyz轴
      WellAnalysis.interWell(wellId, 1, isAddPoint).then((res) => {
        // console.log("interWell", res);
        holeData.value = res.content;
        renderChart(holeData.value, svgUrl.value);
      });
    } else {
      console.log('测井数据不存在');
      spinning.value = false;
    }
  })
}
// 获取岩性信息
// function getLithList(startDepth, endDepth, lithologyId) {
//   pixelCoord.value = chart.value.convertToPixel("grid", [0, -endDepth]);
//   headPixelCoord.value = chart.value.convertToPixel("grid", [0, -startDepth]);
//   getOne(lithologyId).then((res) => {
//     svgUrl.value = `/dev-api/ufs/preview/${res.lithologyFile}`;
//     renderChart(holeData.value, svgUrl.value);
//   });
// }
// 获取岩性信息
function getLithList(lithologData, level = []) {
  coord.value = [];
  let stable = [];
  //井壁稳定性等级
  if (level !== []) {
    let levelStart = 0;
    level.forEach((res) => {
      let color = "";
      if (res.is_Not_Safe == "危险") {
        color = "#FF410E";
      } else if (res.is_Not_Safe == "基本安全") {
        color = "#FFE25E";
      } else if (res.is_Not_Safe == "安全") {
        color = "#0CF0A6";
      }
      stable.push({ start: levelStart, end: res.depth, danger: color });
      levelStart = res.depth;
    });
  }
  //岩性数据
  lithologData.forEach((res) => {
    const ltDepth = holeData.value[holeData.value.length - 1].true_vertical_depth;
    const pixel = chart.value.convertToPixel("grid", [ltDepth - 900, -res.end]); //convertToPixel将数据坐标转化为像素坐标
    const headPixel = chart.value.convertToPixel("grid", [ltDepth - 900, -res.start]);
    coord.value.push({
      pixelCoord: pixel,
      headPixelCoord: headPixel,
      svgUrl: `/dev-api/ufs/preview/${res.lithologyFile}`,
    });
  });
  chart.value.clear();
  renderChart(holeData.value, coord.value, stable);
}
defineExpose({ getLithList });

function getView(type) {
  renderChart(holeData.value, coord.value, [], type);
}
// 画图
function renderChart(dataRows, formLithology, stable = [], type) {
  // console.log("----level------level-----level-----", stable);
  spinning.value = true;
  const data = [[0, 0, 0]];
  const drill = [];
  const casing = [];
  const risk = [];
  const wellbore = [];
  const passResult = [];
  let lithologySvg = [];
  lithologyImg.value = [];
  const depth = dataRows[dataRows.length - 1].true_vertical_depth;
  dataRows.forEach((element) => {
    if (type == '右视图') {
      const x = element.east;
      const y = element.north;
      const z = -element.true_vertical_depth;
      data.push([x, y, z]);
    } else {
      const x = element.north;
      const y = element.east;
      const z = -element.true_vertical_depth;
      data.push([x, y, z]);
    }
    // console.log(data)
  });
  const divElement = chartContainer.value;
  chart.value = echarts.init(chartContainer.value);
  //岩性信息
  let svgWidth = 20;
  let t = [];
  formLithology?.forEach((item) => {
    const step = parseInt((item.pixelCoord[1] - item.headPixelCoord[1]) / svgWidth) - 1;
    for (let i = 0; i < step; i++) {
      t.push(
        {
          type: "image",
          style: {
            image: item.svgUrl,
            x: item.pixelCoord[0],
            y: item.pixelCoord[1] - (i + 1) * svgWidth,
            width: 85,
            height: svgWidth,
            opacity: 0.9,
          },
        },
        // {
        //   type: "image",
        //   style: {
        //     image: item.svgUrl,
        //     x: item.pixelCoord[0],
        //     y: item.pixelCoord[1] - (i + 1) * svgWidth,
        //     width: 100,
        //     height: svgWidth,
        //     opacity: 0.9,
        //   },
        // }
      );
    }
    t.push(
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0],
          y: item.headPixelCoord[1],
          width: 85,
          height: svgWidth,
          opacity: 0.9,
        },
      },
      // {
      //   type: "image",
      //   style: {
      //     image: item.svgUrl,
      //     x: item.pixelCoord[0],
      //     y: item.headPixelCoord[1],
      //     width: 100,
      //     height: svgWidth,
      //     opacity: 0.9,
      //   },
      // },
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0],
          y: item.headPixelCoord[1] + 20,
          width: 85,
          height: svgWidth,
          opacity: 0.9,
        },
      },
      // {
      //   type: "image",
      //   style: {
      //     image: item.svgUrl,
      //     x: item.pixelCoord[0],
      //     y: item.headPixelCoord[1] + 20,
      //     width: 100,
      //     height: svgWidth,
      //     opacity: 0.9,
      //   },
      // }
    );
    lithologyImg.value = t;
  });

  //风险井段
  props.echartsData?.wellRiskSectionList?.forEach((res) => {
    risk.push([
      {
        name: res.stratumName,
        yAxis: -res.start,
      },
      {
        yAxis: -res.end,
      },
    ]);
  });
  const riskRange = {
    itemStyle: {
      color: "rgba(255, 173, 177, 0.4)",
    },
    label: {
      show: true,
      position: "right", // 将 label 放在区域图的最右侧
      offset: [-120, 0], // 设置 label 的偏移量
    },
    data: [...risk],
  };
  // 钻头
  props.echartsData?.drillInformationList.forEach((res) => {
    let drillData = data.filter((e) => e[2] >= -res.deep);
    drill.push({
      type: "line",
      data: drillData.length == 1 ? [[0, 0, 0], [0, 0, -res.deep],] : drillData,
      // 变得圆滑
      smooth: true,
      // 隐藏折点
      symbolSize: 0.0000001,
      encode: {
        x: 0,
        y: 2,
        tooltip: [1, 2],
      },
      lineStyle: {
        opacity: 0.84,
        // color: "#808080",
        color: "#130C7A",
        width: res.diameter * 0.2,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
        shadowBlur: 15
      },
    });
  });
  //添加风险井段内容
  drill[drill.length - 1].markArea = riskRange;

  // 套管
  let numCasing = 1;
  props.echartsData.casingList.forEach((res) => {
    const numArray = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
    // console.log("---------res--------", res);
    let casingData = data.filter((e) => e[2] >= -res.deep);
    if (res.deep !== 0) {
      casing.push({
        type: "line",
        //判断 （套管终点到没到测井的起点）
        data: casingData.length == 1 ? [[0, 0, 0], [0, 0, -res.deep],] : casingData,
        // 变得圆滑
        smooth: true,
        // 隐藏折点
        showSymbol: false,
        name: res.name,
        endLabel: {
          show: true,
          lineHeight: 20,
          formatter: `{a|———>${numArray[numCasing]}开套管\n              垂深:${res.deep}m Φ${res.innerDiameter}mm}`,
          rich: {
            a: {
              fontWeight: "bold", // 加粗
              fontSize: 16, // 字体大小
              color: "#1E90FF", // 文字颜色
              textBorderColor: '#FFFFFF', //描边颜色
              textBorderWidth: 3, //描边宽度
            },
          },
        },
        encode: {
          x: 0,
          y: 2,
        },
        lineStyle: {
          opacity: 0.9,
          // color: "#000000",
          color: "#7E84F7",
          width: res.innerDiameter * 0.2 - 10,
          // shadowColor: '#808080',
          // shadowBlur: 5
        },
      });
    }
    numCasing = numCasing + 1;
  });
  //井壁稳定性
  stable?.forEach((res) => {
    wellbore.push({
      type: "line",
      tooltip: {
        trigger: "axis",
        formatter: "Temperature : <br/>{b}km : {c}°C",
      },
      data: [
        [-depth + 250, -res.start],
        [-depth + 250, -res.end],
      ],
      // 变得圆滑
      smooth: true,
      // 隐藏折点
      symbolSize: 0.0000001,
      encode: {
        x: 0,
        y: 2,
        tooltip: [1, 2],
      },
      lineStyle: {
        opacity: 1,
        color: res.danger,
        width: 40,
      },
    });
  });
  //通过性分析
  if (props.pass !== []) {
    props?.pass?.forEach((res) => {
      let passData = data.filter((e) => e[2] >= -res.deep);
      passResult.push({
        type: "line",
        symbol: "triangle",
        data: [[passData[passData.length - 1][0], -res.deep]],
        symbolSize: [25, 15],
        itemStyle: {
          color: "red", // 标志的颜色
          borderColor: "yellow", // 标志的边框颜色
          borderWidth: 3, // 标志的边框宽度
        },
      });
    });
  }
  //左视图
  const option = ref({
    animation: false,
    grid: {
      x: 50,
      y: 20,
      x2: 50,
      y2: 20,
      borderWidth: 1,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
      showContent: false,
    },
    xAxis: {
      type: "value",
      scale: true,
      min: -depth, //原数值 -(depth/2)
      max: depth, //原数值 depth/2
      axisLabel: "",
    },
    yAxis: {
      type: "value",
      scale: true,
      axisLabel: {
        formatter: function (value) {
          return Math.abs(value);
        },
      },
    },

    graphic: [...lithologyImg.value],
    series: [...drill, ...casing, ...passResult, ...wellbore],
    //岩性图
  });
  chart.value.setOption(option.value);
  lithologyImg.value.splice(0, lithologySvg.length);
  spinning.value = false;
  canvaImg();
}
//截图
function canvaImg() {
  const formData = new FormData();
  html2canvas(chartContainer.value).then((canvas) => {
    const imageData = canvas.toDataURL("image/png");
    formData.append("chartType", "井深结构图");
    formData.append("file", imageData);
    formData.append("schemeId", localStorage.getItem("schemeId"));
    upFile(formData).then((res) => {
      console.log("yes");
    });
  });
}
</script>
